package rr_test_client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class TestClient implements Runnable {

	TCMainWindow window;
	TCMessageUtil messageUtil = new TCMessageUtil(this);
	StringBuilder messageBoardText = new StringBuilder("");
	String hostName = "Bob-Lap1";
	String outMessage;
	int playerId;
	int portNum = 32_314;
	int score;
	Socket socket = null;
	PrintWriter printWrtr = null;
	BufferedInputStream bis = null;
	InputStreamReader isr = null;
	boolean isTextToSend = false;

	// TestClient constructor
	public TestClient(TCMainWindow window) {
		this.window = window;

		// establish a connection to the server
		try {
			InetAddress address = InetAddress.getByName(hostName);
			socket = new Socket(address, portNum);
		} catch (IOException iOException) {
			iOException.printStackTrace();
		}

		// get and wrap input stream
		try {
			bis = new BufferedInputStream(socket.getInputStream());
			isr = new InputStreamReader(bis);
		} catch (IOException iOException) {
			iOException.printStackTrace();
		}

		// instantiate and start message listening thread
		new Thread(this).start();
	}

	public void sendText(String outMessage) {
		this.outMessage = outMessage;
		isTextToSend = true;

		// write new message to the output stream of the connection
		if (isTextToSend) {
			
			// get and wrap output stream
			try {
				printWrtr = new PrintWriter(socket.getOutputStream(), true);
				printWrtr.println(this.outMessage);
			} catch (IOException iOException1) {
				iOException1.printStackTrace();
			}
			
			isTextToSend = false;	
		}
	}

	public void run() {
		String inMessage;
		boolean isListening = true;

		try {

			// get and wrap input stream
			BufferedReader bufRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			while (isListening) {	
				if ((inMessage = bufRdr.readLine()) != null) {
					messageUtil.processMessage(inMessage);
					postMessage(inMessage);
				}
			}
		} catch (IOException iOException) {
			iOException.printStackTrace();
		}
	}

	public void postMessage(String message) {
		if (messageBoardText.toString().equals("")) {
			messageBoardText.append(message);
			window.display.asyncExec(new Runnable() {
				public void run() {
					if (!window.styledText.isDisposed()) {
						window.styledText.setText(messageBoardText.toString());
					}
				}
			});
		} else {
			messageBoardText.append("\n" + message);
			window.display.asyncExec(new Runnable() {
				public void run() {
					if (!window.styledText.isDisposed()) {
						window.styledText.setText(messageBoardText.toString());
					}
				}
			});
		}
	}
}
